package com.yxj.securityhello.filter;

import com.alibaba.fastjson2.JSON;
import com.mysql.cj.util.StringUtils;
import com.yxj.securityhello.domain.vo.LoginUser;
import com.yxj.securityhello.util.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * @author yangxuejiao
 * @description
 * @createDate 2025/11/3 00:45
 */
//每一个servlet请求，都只会请求一次
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //1.如果是/user/login，直接放行
        String uri = request.getRequestURI();
        if("/user/login".equals(uri)) {
            filterChain.doFilter(request, response);
            return;
        }
        //2.判断token令牌是否有效
        String token = request.getHeader("Authorization");
        if(StringUtils.isNullOrEmpty(token)) {
            throw new RuntimeException("token令牌为空");
        }
        //3.校验令牌
        LoginUser loginUser = null;
        try {
            Claims claims = JwtUtils.parseJWT(token);
            String loginUserString = claims.getSubject();
            //吧字符串转换为loginUser对象
            loginUser = JSON.parseObject(loginUserString, LoginUser.class);
            System.out.println(loginUser);
        } catch (Exception e) {
            throw new RuntimeException("token校验失败");
        }
        //4.吧验证完获取到的用户信息再次放入springsecurity的上下文中
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser.getUsername(), null, null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //放行
        filterChain.doFilter(request, response);
    }
}
